package com.shuqi.activity.adapter;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.shuqi.activity.BookShelfActivity;
import com.shuqi.activity.viewport.CircleProgressBarView;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.utils.Log4an;
import com.shuqi.common.utils.SqImageManager;
import com.shuqi.controller.R;
import com.shuqi.database.model.BookMarkInfo;
import com.shuqi.download.database.DownloadInfo;
import com.shuqi.download.util.DownloadStatus;
import com.shuqi.model.manager.DownLoadShuqiBook;
import com.shuqi.model.manager.MyAccountManager;

/**
 * 书架Adapter
 * 
 * @author Jianda.Yang
 * 
 * @Date 2014-1-13 下午6:55:05
 */
public class BookShelfAdapter extends BaseAdapter {
    final LruCache<String, Bitmap> lruCache = new LruCache<String, Bitmap>(20);

    public List<BookMarkInfo> mList;

    private BookShelfActivity context;

    private HashMap<ViewHolder, String> mCacheUIMap = new HashMap<ViewHolder, String>();

    private HashMap<String, BookMarkInfo> mCacheListMap = new HashMap<String, BookMarkInfo>();

    public DecimalFormat formater = new DecimalFormat("#0.#");

    private int mCurrentType = TYPE_NORMAL;

    public final static int TYPE_HEAD = 0;

    public final static int TYPE_NORMAL = 1;

    public final static int TYPE_FOOTLER = 2;

    public final static int TYPE_MAX = 3;

    private int mCurrentCount;

    private boolean mIsAddFooter = false;

    public BookShelfAdapter(BookShelfActivity context) {
        this.context = context;
    }

    public void setListData(List<BookMarkInfo> list) {
        mList = list;
        if (mCacheUIMap != null) {
            mCacheUIMap.clear();
        }
        buildCacheListMap();
        this.notifyDataSetChanged();
    }

    // 添加头部空白，根据list的size判断是否添加底部的空白
    @Override
    public int getCount() {
        mIsAddFooter = false;
        if (mList == null) {
            mCurrentCount = 3;
            return mCurrentCount;
        }
        int size = mList.size();
        mIsAddFooter = size > 6;
        if (size < 3) {
            size = 3;
        } else if (size >= 3) {
            // 补齐3的倍数
            if (size % 3 != 0) {
                size += 3 - size % 3;
            } else {// 防止没有第四行的加号
                size += 3;
            }
        }
        mCurrentCount = size + 3 + (mIsAddFooter ? 3 : 0);
        return mCurrentCount;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public int getViewTypeCount() {
        return TYPE_MAX;
    };

    @Override
    public int getItemViewType(int position) {
        mCurrentType = TYPE_NORMAL;
        if (position < 3) {
            mCurrentType = TYPE_HEAD;
        }
        if (mIsAddFooter) {
            if (position >= mCurrentCount - 3) {
                mCurrentType = TYPE_FOOTLER;
            }
        }
        return mCurrentType;
    }

    @Override
    public View getView(int position, View view, ViewGroup arg2) {
        if (mCurrentType == TYPE_HEAD || mCurrentType == TYPE_FOOTLER) {
            if (view == null) {
                LayoutInflater inflater = LayoutInflater.from(context);
                view = inflater.inflate(R.layout.bookshelf_head_view, null);
            }
        } else if (mCurrentType == TYPE_NORMAL) {
            ViewHolder holder;
            if (view == null) {
                LayoutInflater inflater = LayoutInflater.from(context);
                view = inflater.inflate(R.layout.item_bookshelfadapter_gridview, null);
                holder = new ViewHolder(view);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            if ((position % 3) == 0) {
                holder.lineImageView.setBackgroundResource(R.drawable.bookshelf_frame_left);
            } else if ((position % 3) == 2) {
                holder.lineImageView.setBackgroundResource(R.drawable.bookshelf_frame_right);
            } else {
                holder.lineImageView.setBackgroundResource(R.drawable.bookshelf_frame_midle);
            }
            bindView(position - 3, view, holder);
        }
        return view;
    }

    private void bindView(final int position, View view, ViewHolder holder) {
        String mapValue = "";
        boolean isRealData = position < (mList == null ? 0 : mList.size());// 当前项是真实数据
        boolean isHasData = mList != null && mList.size() > 0; // 有显示数据
        holder.bookUpdateImg.setVisibility(View.GONE);
        if (isHasData) {
            if (isRealData) {
                BookMarkInfo info = mList.get(position);
                if (info == null) {
                    return;
                }
                mapValue = info.getUniqueKey();
                holder.shadowImageView.setVisibility(View.VISIBLE);
                holder.bg_shadow.setVisibility(View.VISIBLE);
                holder.coverLayout.setVisibility(View.VISIBLE);
                holder.titleTextView.setVisibility(View.VISIBLE);
                holder.perTextView.setVisibility(View.VISIBLE);
                holder.titleTextView.setText(info.getBookName());
                holder.perTextView.setText((info.getPercent() > 0 ? "读至"
                        + formater.format(Float.valueOf(info.getPercent())) : "读至0")
                        + "%");

                // 显示图片
                showImageView(holder, position, view);

                // for SHUQIA-400
                if (info.getBookCoverImgUrl() == null || info.getBookCoverImgUrl().length() == 0) {
                    showLocalTxtBookName(holder.localTxtNameTextView, true, info.getBookName());
                }
                // 显示本地书籍封面的书名
                else {
                    showLocalTxtBookName(holder.localTxtNameTextView,
                            info.getBookType() == BookMarkInfo.TYPE_LOCAL_BOOKMARK,
                            info.getBookName());
                }

                // 编辑状态 显示删除按钮
                setChecked(holder, isIndel(info.getUniqueKey()));
                showShadowView(holder, false);
                showDownView(holder, false);

                // 显示下载状态
                // boolean isNeedDown = info.isNeedDown();
                if (info.getBookType() == BookMarkInfo.TYPE_NEW_PAY_BOOKMARK) {
                    Log4an.e("yjd", "【adapter】info.getBookId()=" + info.getBookId());
                    DownloadInfo doInfo =
                            DownLoadShuqiBook.getInstace().getDownBookState(
                                    MyAccountManager.getInstance(ShuqiApplication.getContext())
                                            .getUserId(), info.getBookId());
                    Log4an.e("yjd", "【adapter】doInfo is null=" + (doInfo == null));
                    if (doInfo != null) {
                        boolean isNeedDown = info.isNeedDown(doInfo.getDownloadStatus());
                        Log4an.e("yjd", "【adapter】isNeedDown=" + isNeedDown + " getDownloadStatus="
                                + doInfo.getDownloadStatus());
                        showDownView(holder, isNeedDown);
                        if (isNeedDown) {
                            int state = doInfo.getDownloadStatus();
                            float per = doInfo.getDownloadPercent();
                            Log4an.i("yjd", "【adapter】1.state=" + state + ",per=" + per);
                            initCircleProgressBar(doInfo.getBookId(), state, per, holder);

                        }
                        // 显示阴影
                        showShadowView(holder, isNeedDown);
                    }
                }


                // 设置更新图标
                if (info.getUpdateFlag() == BookMarkInfo.UPDATE_FLAG) {
                    holder.bookUpdateImg.setVisibility(View.VISIBLE);
                }

                // 设置listener
                // initViewListener(view, position);

            } else {

                if (position == mList.size()) {
                    holder.titleTextView.setVisibility(View.GONE);
                    showLocalTxtBookName(holder.localTxtNameTextView, false, null);
                    holder.coverLayout.setVisibility(View.VISIBLE);
                    holder.perTextView.setVisibility(View.GONE);
                    holder.isDelImg.setVisibility(View.GONE);
                    holder.imageView.setImageResource(R.drawable.bookshelf_default);
                    holder.imageViewFrame.setVisibility(View.VISIBLE);
                    showDownView(holder, false);
                    showShadowView(holder, false);
                    holder.shadowImageView.setSelected(false);

                    if (context.isRedact)// 编辑状态点击更多无影响
                        holder.shadowImageView.setVisibility(View.GONE);
                    else
                        holder.shadowImageView.setVisibility(View.VISIBLE);

                } else {
                    holder.coverLayout.setVisibility(View.INVISIBLE);
                    holder.titleTextView.setVisibility(View.INVISIBLE);
                    holder.bg_shadow.setVisibility(View.GONE);
                }


                // holder.coverLayout.setVisibility(View.INVISIBLE);
                // holder.titleTextView.setVisibility(View.INVISIBLE);
            }
        } else {
            // 没有数据显示 +
            holder.titleTextView.setVisibility(View.GONE);
            showLocalTxtBookName(holder.localTxtNameTextView, false, null);
            if (position == 0) {
                holder.coverLayout.setVisibility(View.VISIBLE);
                holder.perTextView.setVisibility(View.GONE);
                holder.isDelImg.setVisibility(View.GONE);
                holder.imageViewFrame.setVisibility(View.VISIBLE);
                holder.imageView.setImageResource(R.drawable.bookshelf_default);
                showDownView(holder, false);
                showShadowView(holder, false);
                // initViewClickListener(view, position);

            } else {
                holder.coverLayout.setVisibility(View.INVISIBLE);
                holder.imageView.setImageDrawable(null);
                holder.bg_shadow.setVisibility(View.GONE);
            }
        }
        addUIMap(holder, mapValue);
    }

    private void showLocalTxtBookName(TextView tv, boolean isLocalTxt, String bookName) {
        if (isLocalTxt) {
            tv.setVisibility(View.VISIBLE);
            tv.setText(bookName);
        } else {
            tv.setVisibility(View.GONE);
        }
    }

    private void showImageView(ViewHolder holder, final int position, View view) {
        holder.imageView.setTag(position);
        BookMarkInfo bookInfo = mList.get(position);
        if (bookInfo != null) {
            if (BookMarkInfo.TYPE_LOCAL_BOOKMARK == bookInfo.getBookType()) {
                // 本地书籍
                holder.imageViewFrame.setVisibility(View.GONE);
                String imgurl = bookInfo.getBookCoverImgUrl();
                if (String.valueOf(BookMarkInfo.LOCAL_IMAGE_BLUE).equals(imgurl)) {
                    holder.imageView.setImageDrawable(ShuqiApplication.getContext().getResources()
                            .getDrawable(BookMarkInfo.LOCAL_IMAGE_BLUE));
                } else if (String.valueOf(BookMarkInfo.LOCAL_IMAGE_BROWN).equals(imgurl)) {
                    holder.imageView.setImageDrawable(ShuqiApplication.getContext().getResources()
                            .getDrawable(BookMarkInfo.LOCAL_IMAGE_BROWN));
                } else if (String.valueOf(BookMarkInfo.LOCAL_IMAGE_BROWN_RED).equals(imgurl)) {
                    holder.imageView.setImageDrawable(ShuqiApplication.getContext().getResources()
                            .getDrawable(BookMarkInfo.LOCAL_IMAGE_BROWN_RED));
                } else {
                    holder.imageView.setImageDrawable(ShuqiApplication.getContext().getResources()
                            .getDrawable(BookMarkInfo.LOCAL_IMAGE_GRENN));
                }
            } else {
                // 非本地书籍
                holder.imageViewFrame.setVisibility(View.VISIBLE);
                if (TextUtils.isEmpty(bookInfo.getBookCoverImgUrl())) {
                    holder.imageView.setImageDrawable(ShuqiApplication.getContext().getResources()
                            .getDrawable(R.drawable.book_shelf_local_random_brown));
                } else {// TODO
                    SqImageManager.getImageManager().displayImage(bookInfo.getBookCoverImgUrl(),
                            holder.imageView, SqImageManager.IMG_COVER,
                            R.drawable.icon_def_bookimg_rank);

                }

            }
        }
    }

    // 更新下载进度的UI
    public void updateDownloadUI(String bid, int state, float per/* , int oidMax, int downCount */) {
        String bid2 = bid;
        // Log4an.e("yjd", "updateDownloadUI bid=" + bid + ",state=" + state + ",per=" + per);
        Iterator<Entry<ViewHolder, String>> it = mCacheUIMap.entrySet().iterator();
        bid = BookMarkInfo.getDownBookMarkId(bid);
        while (it.hasNext()) {
            Entry<ViewHolder, String> entry = (Entry<ViewHolder, String>) it.next();
            if (entry.getValue().equals(bid)) {
                initCircleProgressBar(bid2, state, per, entry.getKey());
                setChecked(entry.getKey(), isIndel(bid));
                break;
            }
        }
    }

    private boolean isIndel(String bid) {
        if (context.mDelBookMap != null && context.mDelBookMap.containsKey(bid)) {
            return true;
        }
        return false;
    }

    private float mLastPer = 0;// 8.0.1 记录上次的进度和时时更新的进度(为解决等待状态问题)

    private void initCircleProgressBar(String bid, int state, float per, ViewHolder holder) {
        int color = R.color.book_paint_bg;
        holder.bookDownProgressbar.setPaintBgColor(color);
        showShadowView(holder, true);
        if (per >= 0) {// 8.0.1 为解决初始化进入与时时变化时，进度的保留
            mLastPer = (int) per;
        }
        switch (state) {
            case DownloadStatus.STATE_WAIT:
            case DownloadStatus.STATE_RUN:
            case DownloadStatus.STATE_UNZIP: {
                if (holder.bookDownProgressbar.getVisibility() == View.GONE) {
                    showDownView(holder, true);
                }
                color = R.color.book_paint_blue;
                holder.bookDownProgressbar.setPaintColor(color);
                String text = per + "%";
                if (state == DownloadStatus.STATE_WAIT) {
                    holder.bookDownProgressbar
                            .setPaintBgColor(R.color.book_paint_bg_half_transparency);
                    holder.bookStateIconImg.setImageResource(R.drawable.bookshelf_down_wait);
                    if (per <= 0) {// 8.0.1 当下载层传入等待状态，且per为-1.0时，要保持进度显示之前的进度
                        text = mLastPer + "%";
                        holder.bookDownProgressbar.setProgressBySize((int) mLastPer);
                    }
                } else {
                    color = R.color.book_paint_blue;
                    holder.bookStateIconImg.setImageResource(R.drawable.bookshelf_down_pause);
                    holder.bookDownProgressbar.setProgressBySize((int) per);
                }
                holder.bookTapTextView.setText(text);
            }
                break;
            case DownloadStatus.STATE_DONE:
                showDownView(holder, false);
                showShadowView(holder, false);
                break;
            case DownloadStatus.STATE_STOP:
            case DownloadStatus.STATE_UNZIP_STOP:
            case DownloadStatus.STATE_ERR_CONN:
            case DownloadStatus.STATE_ERR_DB: {
                DownloadInfo doInfo = null;
                if (!TextUtils.isEmpty(bid)) {
                    doInfo =
                            DownLoadShuqiBook.getInstace().getDownBookState(
                                    MyAccountManager.getInstance(ShuqiApplication.getContext())
                                            .getUserId(), bid);
                }
                if (doInfo != null) {
                    if (holder.bookDownProgressbar.getVisibility() == View.GONE) {
                        showDownView(holder, true);
                    }
                    holder.bookStateIconImg.setImageResource(R.drawable.bookshelf_down_error);
                    color = R.color.book_paint_red;
                    holder.bookDownProgressbar.setPaintColor(color);
                    if (per < 0) {// 8.0.1 当下载层传入等待状态，且per为-1.0时，要保持进度显示之前的进度
                        holder.bookDownProgressbar.setProgressBySize((int) mLastPer);
                        holder.bookTapTextView.setText(mLastPer + "%");
                    } else {
                        holder.bookDownProgressbar.setProgressBySize((int) per);
                        holder.bookTapTextView.setText((int) per + "%");
                    }
                } else {
                    showDownView(holder, false);
                }
            }
                break;
            default:
                break;
        }
    }

    // 显示阴影， 下载和删除模式下显示阴影
    private void showShadowView(ViewHolder holder, boolean isDown) {
        if (!context.isRedact) {
            holder.shadowImageView.setSelected(isDown);
        } else {
            holder.shadowImageView.setSelected(true);
        }
    }

    // 展示下载的view
    private void showDownView(ViewHolder holder, boolean isShow) {
        if (isShow) {
            holder.netRlLayout.setVisibility(View.VISIBLE);
            holder.bookDownProgressbar.setVisibility(View.VISIBLE);
            holder.bookTapTextView.setVisibility(View.VISIBLE);
            holder.bookStateIconImg.setVisibility(View.VISIBLE);
        } else {
            holder.netRlLayout.setVisibility(View.GONE);
            holder.bookDownProgressbar.setVisibility(View.GONE);
            holder.bookTapTextView.setVisibility(View.GONE);
            holder.bookStateIconImg.setVisibility(View.GONE);
        }
    }

    // 构建UI map
    private void addUIMap(ViewHolder holder, String bid) {
        if (mCacheUIMap == null) {
            mCacheUIMap = new HashMap<BookShelfAdapter.ViewHolder, String>();
        }
        mCacheUIMap.put(holder, bid);
    }

    public void buildCacheListMap() {
        if (mCacheListMap != null) {
            mCacheListMap.clear();
            if (mList != null) {
                for (BookMarkInfo info : mList) {
                    mCacheListMap.put(info.getUniqueKey(), info);
                }
            }
        }
    }

    public void onDestroy() {
        if (mCacheListMap != null) {
            mCacheListMap.clear();
            mCacheListMap = null;
        }
        if (mCacheUIMap != null) {
            mCacheUIMap.clear();
            mCacheUIMap = null;
        }

        mList = null;
    }

    /**
     * 
     * @param checked
     * @param isRedact
     */
    private void setChecked(ViewHolder holder, boolean isChecked) {
        if (context.isRedact) {
            holder.isDelImg.setVisibility(View.VISIBLE);
            holder.isDelImg.setImageResource(!isChecked ? R.drawable.checkbox_item_n
                    : R.drawable.checkbox_item_c);
        } else {
            holder.isDelImg.setVisibility(View.GONE);
        }
    }

    static class ViewHolder {

        private ImageView imageView;// 封面

        private ImageView imageViewFrame;// 封面

        private RelativeLayout coverLayout;// 封面布局

        private ImageView lineImageView;// 数据横框图片

        private TextView titleTextView;// 书籍名称

        private TextView perTextView;// 书籍进度

        private ImageView isDelImg;// 是否删除书签的图片

        private ImageView shadowImageView;// 选中效果

        private ImageView bg_shadow;// 选中效果

        private CircleProgressBarView bookDownProgressbar; // 下载进度圈

        private TextView bookTapTextView; // 现在百分比
        /** 下载状态 */
        private ImageView bookStateIconImg;

        private ImageView bookUpdateImg;// 更新图标

        private TextView localTxtNameTextView; // 本地数据封面展示书名

        private RelativeLayout netRlLayout;

        ViewHolder(View view) {
            this.bg_shadow = (ImageView) view.findViewById(R.id.bookshelf_bg_shadow);
            this.imageView = (ImageView) view.findViewById(R.id.bkshelfadapter_img);
            this.imageViewFrame = (ImageView) view.findViewById(R.id.bkshelfadapter_frame);
            this.titleTextView = (TextView) view.findViewById(R.id.bkshelfadapter_title_tv);
            this.lineImageView = (ImageView) view.findViewById(R.id.bkshelfadapter_line_img);
            this.coverLayout = (RelativeLayout) view.findViewById(R.id.bkshelfadapter_cover_rel);
            this.isDelImg = (ImageView) view.findViewById(R.id.bkshelfadapter_del_img);
            this.perTextView = (TextView) view.findViewById(R.id.bkshelfadapter_per_tv);
            this.shadowImageView = (ImageView) view.findViewById(R.id.bkshelfadapter_shadow_img);
            netRlLayout =
                    (RelativeLayout) view.findViewById(R.id.bkshelfadapter_book_down_state_rel);
            this.bookDownProgressbar =
                    (CircleProgressBarView) view
                            .findViewById(R.id.bkshelfadapter_circleProgressbar);
            this.bookDownProgressbar.setPaintSize(3);
            this.bookTapTextView = (TextView) view.findViewById(R.id.bkshelfadapter_down_tap);
            this.bookStateIconImg =
                    (ImageView) view.findViewById(R.id.bkshelfadapter_book_down_state_icon);
            this.bookUpdateImg = (ImageView) view.findViewById(R.id.bkshelfadapter_img_update);
            this.localTxtNameTextView =
                    (TextView) view.findViewById(R.id.bkshelfadapter_local_txtName_tv);
        }
    }

}
